package com.skit.main.adapter

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.skit.main.R
import com.skit.main.utils.ScreenUtils
import kotlinx.android.synthetic.main.main_img_item.view.*

/**
 * @author shuike <a href="mailto:shuike007@gmail.com">Contact me.</a>
 * @version 1.0
 * @since  2020/6/3
 */
class ImageAdapter(private val imgList: MutableList<String>, private val count: Int = 3) :
    RecyclerView.Adapter<ImageAdapter.ViewHolder>() {

    var onClickListener: View.OnClickListener? = null
    var onDeleteClick: ((Int) -> Unit?)? = null


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val imageView: ImageView = itemView.image
        val delete: ImageView = itemView.delete
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.main_img_item, parent, false)
        val layoutParams = view.layoutParams
        val width: Int = ScreenUtils.getScreenWidth() / count
        layoutParams.width = width
        layoutParams.height = width
        view.layoutParams = layoutParams

        return ViewHolder(view)
    }

    override fun getItemCount(): Int = imgList.size

    fun notifyChanged() {
        if (imgList.size == 10 && imgList.first() == "add") {
            imgList.removeAt(0)
        } else if (imgList.size < 9 && imgList.first() != "add") {
            imgList.add(0, "add")
        }
        notifyDataSetChanged()
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        if ("add" == imgList[position]) {
//            Glide.with(holder.itemView).load("file:///android_asset/add.jpg").into(holder.imageView)
            holder.imageView.setImageResource(R.drawable.ic_add_white_48dp)
            holder.imageView.setBackgroundColor(
                ContextCompat.getColor(holder.imageView.context, R.color.greyWhite)
            )
            holder.delete.visibility = View.GONE
            holder.itemView.setOnClickListener {
                onClickListener?.onClick(holder.itemView)
            }
        } else {
            Glide.with(holder.itemView).load(imgList[position]).into(holder.imageView)
            holder.delete.visibility = View.VISIBLE
            holder.itemView.setOnClickListener {

            }
            holder.delete.setOnClickListener {
                onDeleteClick?.invoke(position)
            }
        }
    }

}